﻿using LightCAD.Core;
using LightCAD.MathLib;
using LightCAD.Model;
using LightCAD.Three;
using QdWater;
using System.Collections.Generic;
using System.Linq;
using Shape = LightCAD.Three.Shape;

namespace QdWater
{
    public class Pipe3dAction : ComponentInstance3dAction
    {
        public override List<Object3D> Render(IComponentInstance cptIns)
        {
            var pipe = cptIns as LcPipe;
            var pipeDef = pipe.Definition as LcPipeDef;
            var result = new List<Object3D>() { };

            foreach (var line2D in pipe.GetBaseLines())
            {

                //Line2d line2D = new Line2d(start2, end2);
                //var pipeLine = pipe.BaseLine;
                var pipeBtm = pipe.Bottom;
                var start = line2D.Start.ToThree(pipeBtm);
                var end = line2D.End.ToThree(pipeBtm);

                var pipeRadius = pipe.Width / 2;
                var pipeLen = start.DistanceTo(end);
                var geo = new CylinderGeometry(pipeRadius, pipeRadius, pipeLen);
                Quaternion quaternion = new Quaternion().SetFromUnitVectors(new Vector3(0, 1, 0), line2D.Dir.ToVector3());
                Matrix4 matrix = new Matrix4().MakeTranslation(0, pipeLen / 2, 0);
                matrix.Premultiply(new Matrix4().MakeRotationFromQuaternion(quaternion));
                matrix.Premultiply(new Matrix4().MakeTranslation(start.X, start.Y, start.Z));

                geo.computeVertexNormals();
                geo.SetUV();
                geo.applyMatrix4(matrix);
                var mats = pipeDef.Solid3dProvider.AssignMaterialsFunc(cptIns, null);
                var wallMesh = new Mesh(geo, mats.Select(m => RenderMaterialManager.GetRenderMaterial(m.Uuid)).ToArray());
                result.Add(wallMesh);
            }

            return result;
        }

    }
}